//
//  FirCirNewIDCommentIDdb.m
//  tcpoctest
//
//  Created by apple on 13-4-26.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "FirCirNewIDCommentIDdb.h"
#import "FirCirNewsDataSource.h"

@implementation FirCirNewIDCommentIDdb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists fircirnewcomment(newsid text,\
commentid text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSArray *newidarr = [[DataControl shareControl].fcnewsDS getAllNewsKeys];
    
    for (NSString *strid in newidarr) {
        
        FriendStatus * fs = [[DataControl shareControl].fcnewsDS getNewsByID:strid];
        
        if (fs != nil) {
            
            [fs.commentArr removeAllObjects];
            
            NSString *strsql = [NSString stringWithFormat:@"select commentid \
from fircirnewcomment where newsid = '%@'",strid];
            
            FMResultSet *s = [db executeQuery:strsql];
            while ([s next]) {
                [fs.commentArr addObject:[s stringForColumn:@"commentid"]];
            }
        }
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertNewComment:(NSString *)newid withCommentID:(NSString *)commentid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"select * from fircirnewcomment \
where commentid = '%@'",commentid];
    
    FMResultSet *s = [db executeQuery:strsql];
    if (![s next]) {
        strsql = [NSString stringWithFormat:@"insert into fircirnewcomment \
(newsid,commentid) values('%@','%@')"
                  ,newid
                  ,commentid];
        
        [db executeUpdate:strsql];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)delNewCommentByNewId:(NSString *)newid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"delete FROM fircirnewcomment WHERE newsid='%@'"
                        ,newid];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
